package controller

import (
	"app-webapi/comm/g"
	"app-webapi/comm/response"
	"app-webapi/entity"
	"app-webapi/entity/dto"
	"app-webapi/service"
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	"strconv"
)

// Test 访问地址 127.0.0.1:58782
func Test(c *gin.Context) {
	response.Success(g.Selected, "OK", c)
}

func TestList(ctx *gin.Context) {
	var testEntityList entity.TestEntityList
	if err := ctx.ShouldBindQuery(&testEntityList); err != nil {
		response.Err(g.ParamInvalid, err.Error(), ctx)
		return
	}
	devices, total, err := service.GetTestEntities(testEntityList)
	if err != nil {
		response.Err(g.NotSelected, err.Error(), ctx)
		return
	}
	response.SuccessPage(g.Selected, devices, total, ctx)
	return
}

func AddTest(ctx *gin.Context) {
	testEntity := entity.TestEntity{}
	if err := ctx.ShouldBindJSON(&testEntity); err != nil {
		response.Err(g.ParamInvalid, err.Error(), ctx)
		return
	}
	err := service.CreateTestEntity(testEntity)
	if err != nil {
		response.Err(g.NotCreated, err.Error(), ctx)
		return
	}
	// 添加记录
	//service.GenerateLog(ctx, entity.CreateOperation, "新增告警策略\""+params.StrategyName+"\"")
	response.Success(g.Created, nil, ctx)
	return

}

func UpdateTest(ctx *gin.Context) {

	params := dto.TestEntityDto{}
	if err := ctx.ShouldBindJSON(&params); err != nil {
		response.Err(g.ParamInvalid, err.Error(), ctx)
		return
	}

	err := service.UpdateTestEntity(params)
	if err != nil {
		response.Err(g.NotUpdated, err.Error(), ctx)
		return
	}
	// 添加记录
	//service.GenerateLog(ctx, entity.UpdateOperation, "修改告警策略\""+params.StrategyName+"\"")
	response.Success(g.Updated, nil, ctx)
	return

}

func DetailTest(ctx *gin.Context) {
	id := ctx.Param("id")
	iid, _ := strconv.Atoi(id)
	strategyDTO, err := service.DetailTestEntity(iid)
	if err != nil {
		response.Err(g.NotSelected, err.Error(), ctx)
		return
	} else {
		response.Success(g.Selected, strategyDTO, ctx)
	}
	return
}

func DeleteTest(ctx *gin.Context) {
	id := ctx.Param("id")
	iid, err := strconv.Atoi(id)
	if err != nil {
		response.Err(g.ParamInvalid, err.Error(), ctx)
		return
	}

	err = service.DeleteTestEntity(iid)
	if err != nil {
		response.Err(g.NotDeleted, err.Error(), ctx)
		return
	}
	// 添加记录
	//service.GenerateLog(ctx, entity.DeleteOperation, "删除告警策略\""+dest.StrategyName+"\"")
	response.Success(g.Deleted, nil, ctx)
	return

}

func TestDeviceOrder() {
	/**
	  - name: "StopControl"
	    readWrite: "W"
	    isHidden: false
	    resourceOperations:
	      - { deviceResource: "StopControl" }
	      - { deviceResource: "Step" }
	      - { deviceResource: "ChannelId" }
	*/

	background := context.Background()
	client := g.AppService.CommandClient()
	m := make(map[string]interface{}, 2)
	m["ChannelId"] = "2222"
	m["Step"] = "40"
	_, edgeErr := client.IssueSetCommandByNameWithObject(background, "Camera-T", "StopControl", m)
	if edgeErr != nil {
		fmt.Println(edgeErr)
	}
	fmt.Println("")
}
